package com.sdry.system.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdry.common.BaseController;
import com.sdry.common.TableDataInfo;
import com.sdry.system.entity.*;
import com.sdry.system.service.DeptService;
import com.sdry.system.service.PositionService;
import com.sdry.system.service.RoleService;
import com.sdry.system.service.UserService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;


/**
 * @version: 1.0
 * @description: 用户管理
 * @author: cb
 * @create: 2020-01-13 20:18
 **/
@Controller
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private PositionService positionService;

    /**
     * 展示用户信息
     * @return
     */
    @RequestMapping(value = "/showUser")
    public String showUser(Model model) {
        //角色
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0L).select("role_id","role_name");
        List<SysRole> roleDataList = roleService.list(queryWrapper);
        model.addAttribute("roleDataList",roleDataList);
        return "/system/user/userList";
    }

    /**
     * 展示员工信息
     * @return
     */
    @RequestMapping(value = "/showStaff")
    public String showStaff(Model model) {

        //部门
        QueryWrapper<SysDept> queryWrapper02 = new QueryWrapper<>();
        queryWrapper02.eq("del_flag",0L).select("dept_id","dept_name");
        List<SysDept> sysDeptList = deptService.list(queryWrapper02);

        //岗位
        QueryWrapper<SysPosition> queryWrapper03 = new QueryWrapper<>();
        queryWrapper03.eq("del_flag",0L).select("post_id","post_name");
        List<SysPosition> sysPositionList = positionService.list(queryWrapper03);

        model.addAttribute("sysDeptList",sysDeptList);
        model.addAttribute("sysPositionList",sysPositionList);
        return "/system/stff/staffList";
    }

    /**
     * 去修改页面
     * @return
     */
    @RequestMapping(value = "/showUpdateUser")
    @ResponseBody
    public String showUpdateUser(Model model,Long userId) {
        //用户
        SysUser sysUser = userService.getById(userId);
        //角色
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("del_flag",0L).select("role_id","role_name");
        List<SysRole> roleDataList = roleService.list(queryWrapper);
        //用户角色
        List<RoleUser> roleUsers =  userService.queryRoleUserByUserIdList(userId);
        //判断是否选中角色
        for (SysRole sysRole : roleDataList) {
            for (RoleUser roleUser : roleUsers) {
                if (sysRole.getRoleId().equals(roleUser.getRoleId()) ){
                    sysRole.setSelection(true);
                }
            }
        }
        sysUser.setSysRoleList(roleDataList);
        return JSONObject.fromObject(sysUser).toString();
    }



    /**
     * 分页查询
     * @param sysUser 用户对象
     * @return
     */
    @RequestMapping(value = "/queryUserPage" )
    @ResponseBody
    public TableDataInfo queryUserPage(SysUser sysUser) {
        logger.info("员工分页查询 sysUser = {} " + JSONObject.fromObject(sysUser));
        try {
            Page<SysUser> page = new Page(sysUser.getPage(),sysUser.getLimit());
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(sysUser.getRealName())) {
                queryWrapper.eq("log_on",sysUser.getLogOn()).eq("del_flag",0L).like("real_name",sysUser.getRealName());
            }else {
                queryWrapper.eq("log_on",sysUser.getLogOn()).eq("del_flag",0L);
            }
            IPage<SysUser> iPage = userService.page(page,queryWrapper);
            List<SysUser> sysUserList = iPage.getRecords();
            for (SysUser user : sysUserList) {
                SysDept sysDept = deptService.getById(user.getDeptId());
                if (sysDept == null) {
                    user.setDeptName(null);
                }else {
                    user.setDeptName(sysDept.getDeptName());
                }
            }
            return getDataTable(sysUserList,iPage.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("员工分页查询失败");
            return getDataTable(new ArrayList<>(),0L);
        }
    }

    /**
     * 修改员工
     * @param sysUser 用户对象
     * @return String
     */
    @RequestMapping(value = "updateUser")
    @ResponseBody
    public Integer updateUser(SysUser sysUser ,@RequestParam("role[]") String[] role) {
        return userService.updateUser(sysUser, role);
    }

    /**
     * 添加用户
     * @param sysUser 用户对象
     * @return String
     */
    @RequestMapping(value = "addUser")
    @ResponseBody
    public Integer addUser(SysUser sysUser ,String[] roleId) {
        return userService.addRole(sysUser, roleId);
    }

    /**
     * 添加员工
     * @param sysUser 用户对象
     * @return String
     */
    @RequestMapping(value = "addStaff")
    @ResponseBody
    public Integer addStaff(SysUser sysUser ,@RequestParam("postId[]") String[] postId) {
        return userService.addStaff(sysUser, postId);
    }

    /**
     * 修改员工
     * @param sysUser 用户对象
     * @return String
     */
    @RequestMapping(value = "updateStaff")
    @ResponseBody
    public Integer updateStaff(SysUser sysUser ,@RequestParam("postId[]") String[] postId) {
        return userService.updateStaff(sysUser, postId);
    }
    /**
     * 删除员工
     * @param userId 用户对象
     * @return String
     */
    @RequestMapping(value = "deleteUser")
    @ResponseBody
    public Integer deleteUser(Long userId) {
        return userService.deleteUser(userId);
    }


    /**
     * 去员工修改页面
     * @return
     */
    @RequestMapping(value = "/showUpdateStaff")
    @ResponseBody
    public String showUpdateStaff(Long userId) {
        //用户
        SysUser sysUser = userService.getById(userId);
        //岗位员工表
        List<PostUser> postUserList = userService.queryPostUser(sysUser.getUserId());
        //部门
        QueryWrapper<SysDept> queryWrapper02 = new QueryWrapper<>();
        queryWrapper02.eq("del_flag",0L).select("dept_id","dept_name");
        List<SysDept> sysDeptList = deptService.list(queryWrapper02);
        sysUser.setSysDeptList(sysDeptList);
        //岗位
        QueryWrapper<SysPosition> queryWrapper03 = new QueryWrapper<>();
        queryWrapper03.eq("del_flag",0L).select("post_id","post_name");
        List<SysPosition> sysPositionList = positionService.list(queryWrapper03);
        //是否选中岗位
        for (SysPosition sysPosition : sysPositionList) {
            for (PostUser postUser : postUserList) {
                if (sysPosition.getPostId().equals(postUser.getPostId())){
                    sysPosition.setSelected(sysPosition.getPostId());
                }
            }
        }
        sysUser.setSysPositionList(sysPositionList);
        return JSONObject.fromObject(sysUser).toString();
    }

    /**
     * 修改密码展示页面
     * @return
     */
    @RequestMapping(value = "/showChangeUserPaw")
    public String showChangeUserPaw(Model model, HttpServletRequest request) {
        SysUser user = (SysUser) request.getSession().getAttribute("user");
        model.addAttribute("user",user);
        return "/system/user/changePwd";
    }

    /**
     * 修改密码
     * @param userId 用户ID
     * @param oldPad 旧密码
     * @param newPad 新密码
     */
    @RequestMapping(value = "/changeUserPaw")
    @ResponseBody
    public Integer changeUserPaw(Long userId,String oldPad,String newPad) {
        Integer effect = userService.changeUserPaw(userId,oldPad,newPad);
        return effect;
    }
}
